<template>
  <BasicModal v-bind="$attrs" @register="registerModal" :title="title" @ok="handleSubmit" width="40%">
    <BasicForm @register="registerForm" />
  </BasicModal>
</template>

<script lang="ts" setup>
  import { ref, computed, unref } from 'vue';
  import { BasicModal, useModalInner } from '/@/components/Modal';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import { formSchema } from '../goodsconfig.data';
  import { saveOrUpdate } from '../goodsconfig.api';

  // Emits声明
  const emit = defineEmits(['register', 'success']);
  const isUpdate = ref(true);

  // 主题选择相关
  const themeSelectorVisible = ref(false);
  const selectedThemeKeys = ref<string[]>([]);
  const selectedThemeData = ref<any>(null);

  //表单配置
  const [registerForm, { resetFields, setFieldsValue, validate }] = useForm({
    labelWidth: 150,
    schemas: formSchema,
    showActionButtonGroup: false,
  });

  //表单赋值
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    //重置表单
    await resetFields();
    setModalProps({ confirmLoading: false, showCancelBtn: data?.showFooter, showOkBtn: data?.showFooter });
    isUpdate.value = !!data?.isUpdate;
    if (unref(isUpdate)) {
      //表单赋值
      await setFieldsValue({
        ...data.record,
      });
    } else {
      // 新增时生成编码
      const rfqCode = generateRfqCode();
      console.log('Generated RFQ Code:', rfqCode);
      await setFieldsValue({ rfqCode });
    }
  });

  //设置标题
  const title = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

  //表单提交事件
  async function handleSubmit(v) {
    try {
      let values = await validate();
      setModalProps({ confirmLoading: true });
      //提交表单
      await saveOrUpdate(values, isUpdate.value);
      //关闭弹窗
      closeModal();
      //刷新列表
      emit('success', { isUpdate: isUpdate.value, values });
    } finally {
      setModalProps({ confirmLoading: false });
    }
  }

  function generateRfqCode() {
    // 调用后端接口或使用shop_order_num规则生成编码
    // 示例格式：RFQ202312010001
    const date = new Date();
    const dateString = date.toISOString().slice(0, 10).replace(/-/g, '');
    const randomNum = Math.floor(Math.random() * 10000)
      .toString()
      .padStart(4, '0');
    return `QUO${dateString}${randomNum}`;
  }

  // 打开主题选择弹窗
  function openThemeSelector() {
    themeSelectorVisible.value = true;
    selectedThemeKeys.value = [];
    selectedThemeData.value = null;
  }

  // 选择主题变化
  function onSelectThemeChange(selectedKeys, selectedRows) {
    selectedThemeKeys.value = selectedKeys;
    if (selectedRows.length > 0) {
      selectedThemeData.value = selectedRows[0];
    } else {
      selectedThemeData.value = null;
    }
  }

  // 处理主题行点击
  function handleThemeRowClick(record) {
    selectedThemeKeys.value = [record.id];
    selectedThemeData.value = record;
  }

  // 处理主题选择
  function handleThemeSelect(record) {
    selectedThemeKeys.value = [record.id];
    selectedThemeData.value = record;
  }

  // 确认选择主题
  function confirmThemeSelection() {
    if (selectedThemeData.value) {
      setFieldsValue({
        rfqTheme: selectedThemeData.value.rfqTheme,
        // 可以根据需要设置其他相关字段
      });
      themeSelectorVisible.value = false;
    } else {
      // 可以添加提示信息
      console.warn('请先选择一个报价主题');
    }
  }

  // 取消选择主题
  function cancelThemeSelection() {
    themeSelectorVisible.value = false;
    selectedThemeKeys.value = [];
    selectedThemeData.value = null;
  }
</script>

<style lang="less" scoped>
  // 为嵌入的主题选择器添加样式
  :deep(.ant-table) {
    font-size: 12px;
  }

  :deep(.ant-table-thead > tr > th) {
    background-color: #fafafa;
  }
</style>
